package com.wrx.club_management_backend.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wrx.club_management_backend.dto.VenueBookingItem;
import com.wrx.club_management_backend.entity.Venue;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface VenueMapper extends BaseMapper<Venue> {

    /**
     * 检查指定场地在给定时间段是否被预约
     *
     * @param venueId 场地ID
     * @param beginTime 开始时间
     * @param duration 持续时间（分钟）
     * @return 冲突的预约数量，0表示没有冲突
     */
    @Select("SELECT COUNT(*) FROM tb_venue_booking " +
            "WHERE venue_id = #{venueId} " +
            "AND (" +
            "  (begin_time <= #{beginTime} AND DATE_ADD(begin_time, INTERVAL duration MINUTE) > #{beginTime}) OR " +
            "  (begin_time < DATE_ADD(#{beginTime}, INTERVAL #{duration} MINUTE) AND begin_time >= #{beginTime})" +
            ")")
    int checkVenueAvailability(@Param("venueId") Long venueId,
                               @Param("beginTime") String beginTime,
                               @Param("duration") Long duration);



    @Insert("INSERT INTO tb_venue_booking (venue_id, activity_id, begin_time, duration, stat) " +
            "VALUES (#{venueId}, #{activityId}, #{beginTime}, #{duration}, 0)")
    void insertBooking(@Param("venueId") Long venueId,
                       @Param("activityId") Long activityId,
                       @Param("beginTime") String beginTime,
                       @Param("duration") Long duration);


    @Update("UPDATE tb_venue_booking SET stat = 1 WHERE activity_id = #{activityId}")
    int updateBookingStatus(@Param("activityId") Long activityId);

    /**
     * 根据场地ID查询场地占用情况
     * @param venueId 场地ID
     * @return 场地占用情况列表
     */
    @Select("SELECT begin_time as beginTime, duration, activity_id as activityId " +
            "FROM tb_venue_booking " +
            "WHERE venue_id = #{venueId} " +
            "ORDER BY begin_time ASC")
    List<VenueBookingItem> bookingList(@Param("venueId") Long venueId);
}
